#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "statistic.h"
#include <QFileDialog>
#include <QString>
#include <QTextCodec>
#include <QTimer>
#include <QEvent>
#include <iostream>
#include <QKeyEvent>
#include <QDebug>
#include <QTextCharFormat>
#include <QTime>
#include <string.h>
#include <time.h>

int iText = -1, iLine = -1, count = 0;
bool SpaceFlag = false, beginFlag = false;
unsigned int MainWindow::errCount = 0;
unsigned int MainWindow::symCount = 0;
unsigned int MainWindow::speed = 0;
int Statistic::a = 0;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    dialog2 = new LanguageWindow;
    ui->setupUi(this);
    ui->lineEdit->setFocus(Qt::OtherFocusReason);
    backspaceEnable = true;
    connect(ui->action_4, SIGNAL(triggered()),this, SLOT(statistics()));
    symCount = 0;
    speed = 0;
    MainWindow::getFileBeginning();
    ui->action_3->setShortcut(Qt::CTRL + Qt::Key_N);
    ui->action_5->setShortcut(Qt::CTRL + Qt::Key_Q);
    ui->action_4->setShortcut(Qt::CTRL + Qt::Key_R);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_action_triggered()
{
    QTextCodec *tcodec = QTextCodec::codecForName("Windows-1251");
    QString filename = QFileDialog::getOpenFileName(0,
        ("Open Text"), ".", ("Text files (*.txt)"));
    QFile file(filename);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QByteArray Data = file.readAll();
    QString text = tcodec->toUnicode(Data);
    file.close();
    ui->txtEdit->setPlainText(text);
    Statistic::a = 0;
}

void MainWindow::updateTimer()
{
    qtime = qtime.addSecs(1);
    ui->timeEdit->setTime(qtime);
    Statistic::a++;
}

void MainWindow::on_action_3_triggered()
{
    if (ui->txtEdit->toPlainText() == "")
        MainWindow::getFileBeginning();
    if (!beginFlag)
    {
      beginFlag = true;
      ui->lineEdit->installEventFilter(this);
      connect(ui->lineEdit,SIGNAL(cursorPositionChanged(int,int)),this,SLOT(setFocusBegin()));
      connect(ui->lineEdit,SIGNAL(selectionChanged()),this,SLOT(setFocusBegin()));
      timer = new QTimer(this);
      qtime.setHMS(0,0,0);
      connect(timer, SIGNAL(timeout()), this, SLOT(updateTimer()));
      timer->start(1000);
      backspaceEnable = false;
      connect(ui->lineEdit, SIGNAL(textEdited(QString)), this, SLOT(check()));
      MainWindow::cur.movePosition(QTextCursor::Start);
      cur = ui->txtEdit->textCursor();
    }
}

void MainWindow::check()
{
    iText++;
    iLine++;
    MainWindow::symCount++;
    if ((ui->txtEdit->toPlainText()[iText] == ' ') && (ui->lineEdit->text()[iLine] == ' '))
    {
        ui->lineEdit->setText("");
        count = iLine;
        iLine = -1;
        QString s(ui->txtEdit->toPlainText()[iText]);
        cur.movePosition(QTextCursor::Right,
                         QTextCursor::KeepAnchor);
        SpaceFlag = true;

    }
    else if (ui->txtEdit->toPlainText()[iText] != ui->lineEdit->text()[iLine])
    {
             iText--;
             iLine--;
             ui->lineEdit->disconnect();
             ui->lineEdit->backspace();
             connect(ui->lineEdit, SIGNAL(textEdited(QString)),
                     this, SLOT(check()));
             MainWindow::errCount++;
             MainWindow::symCount--;
    }
    else
    {
    QString s(ui->txtEdit->toPlainText()[iText]);
    cur.movePosition(QTextCursor::Right,
                     QTextCursor::KeepAnchor);
    cur.removeSelectedText();
    s = "<font color = red>" + s + "</font>";
    if (SpaceFlag)
    {
        ui->txtEdit->insertPlainText(" ");
        SpaceFlag = false;
    }
    ui->txtEdit->insertHtml(s);
    }
    if (ui->txtEdit->toPlainText()[iText + 2] == '\0')
    {
        stop();
        statistics();
    }
}

bool MainWindow::eventFilter(QObject *obj, QEvent *e)
{
    if (obj == ui->lineEdit)
    {
        if (e->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyE = static_cast<QKeyEvent*>(e);
            if (keyE->key() == Qt::Key_Backspace && !backspaceEnable)
            return true;
            else return QMainWindow::eventFilter(obj, e);
        }
    }
   return QMainWindow::eventFilter(obj, e);
}

void MainWindow::setFocusBegin()
{
    ui->lineEdit->setCursorPosition(ui->lineEdit->text().length());
}

void MainWindow::stop()
{
    if (!qtime.isNull())
    {
        beginFlag = false;
        QColor color(0,0,0);
        iText = -1;
        iLine = -1;
        timer->stop();
        ui->txtEdit->setTextColor(color);
        ui->lineEdit->disconnect();
        backspaceEnable = true;
        ui->txtEdit->clear();
        ui->lineEdit->clear();
        SpaceFlag = false;
    }
}

void MainWindow::statistics()
{
    if (!qtime.isNull())
    {
        stop();
        dialog1 = new Statistic();
        dialog1->show();
        Statistic::a = 0;
    }
}

void MainWindow::getFileBeginning()
{
    srand(time(0));
    QTextCodec *tcodec = QTextCodec::codecForName("Windows-1251");
    QFile data("phrases.txt");
    if (!data.open(QIODevice::ReadOnly)) qDebug() << "No file\n";
    QTextStream stream(&data);
    int lineCount = 0;
    QString s;
    bool a = dialog2->LanguageWindow::getLang();
    if (a == 1)
    {
        int Rand = rand() % 7 + 1;
        while (lineCount != Rand)
        {
            s = data.readLine();
            if(s[0] == '#')
                lineCount++;
        }
        QByteArray text = "";
        do
        {
            s = data.readLine();
            s.resize(s.length()-2);
            s.append(' ');
            text.append(s);
        }
        while(s[0] != '#');
        text.resize(text.length() - 2);
        QString str = tcodec->toUnicode(text);
        qDebug() << str;
        ui->txtEdit->setPlainText(str);
        stream.seek(0);
    }
    else
    {
        int Rand = rand() % 17 + 1 ;
        for (int i = 0; i < 45; i++)
        data.readLine();
        while (lineCount != Rand)
        {
            s = data.readLine();
            if(s[0] == '#')
                lineCount++;
        }
        QByteArray text = "";
        do
        {
            s = data.readLine();
            s.resize(s.length()-2);
            s.append(' ');
            text.append(s);
            qDebug() << Rand << s << endl;
        }
        while(s[0] != '#');
        text.resize(text.length() - 2);
        QString str = tcodec->toUnicode(text);
        qDebug() << str;
        ui->txtEdit->setPlainText(str);
        stream.seek(0);
    }
    data.close();
}

void MainWindow::on_action_5_triggered()
{
    stop();
    MainWindow::getFileBeginning(); // ERROR
    MainWindow::on_action_3_triggered();
}

void MainWindow::on_action_2_triggered()
{
    dialog2->show();
}
